﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using DataLib.Common;
using DataLib.Accounts.Bus;
using DataLib.Accounts.Data;
using DataLib.Model;
using System.Text;

namespace Ewts.Project
{
    public partial class AreaList : System.Web.UI.Page
    {
        string alreadySPName = "";
        public string needShowSPName = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Session["UserInfo"] == null)
                {
                    Response.Redirect("/Accounts/Login.aspx");
                }
                else
                {
                    getCheckBox();
                    DataLib.Model.ServerArea querytmodel = new ServerArea();
                    if (Request["id"] != null && Request["id"].ToString().Trim() != "")
                    {
                        querytmodel.ProjectID = int.Parse(Request["id"].ToString().Trim());
                        hidprojectid.Value = querytmodel.ProjectID.ToString();
                        DataLib.Model.Project pmodel = new DataLib.BLL.Project().GetModel((int)querytmodel.ProjectID);
                        querytmodel.CustomerID = pmodel.CustomerID;
                        querytmodel.ProjectName = pmodel.ProjectName;
                        querytmodel.ProjectNum = pmodel.ProjectNum;
                        querytmodel.Customercode = pmodel.CustomerNum;

                        //2015年4月18日 17:27:04 FIFA
                        querytmodel.CustomerName = pmodel.CustomerName;
                    }

                    if (!string.IsNullOrEmpty(Request.QueryString["areaid"]))
                    {
                        hidareaid.Value = Request.QueryString["areaid"];
                        querytmodel = new DataLib.BLL.ServerArea().GetModel(int.Parse(hidareaid.Value.Trim()));
                        BindUpdateInfo(querytmodel);
                    }
                    
                    GetDetile(querytmodel);

                    bindList(querytmodel);
                 
                }
            }
        }
        


        /// <summary>
        /// 得到界面明细
        /// </summary>
        private void GetDetile(DataLib.Model.ServerArea samodel)
        {
             //2015年4月11日 FIFA 添加判断条件
            if (samodel != null && samodel.CustomerID > 0)
            {
                this.lblCustomerName.Text = samodel.CustomerName;
                this.lblProjectName.Text = samodel.ProjectName;
                this.lblProjectNum.Text = samodel.ProjectNum;                
            }
     
        }
       
        /// <summary>
        /// 绑定服务点checkbox
        /// </summary>
        private void getCheckBox()
        {
            //动态绑定服务点
            int id = 0;
            if (Request["id"] != null && Request["id"].ToString().Trim() != "")
            {
                id = int.Parse(Request["id"].ToString());
            }

            string strwhere = string.Format("IsDel = 0 and ServerAreaID in (select ID from ServerArea where ProjectID = {0})",id);
            if (!string.IsNullOrEmpty(Request.QueryString["ServerPointID"]))
            {
                int pointid = Convert.ToInt32(Request.QueryString["ServerPointID"].ToString());
                DataLib.BLL.ServerPoint seBll = new DataLib.BLL.ServerPoint();
                DataLib.Model.ServerPoint smodel = new DataLib.Model.ServerPoint();
                smodel = seBll.GetModel(pointid);
                strwhere = string.Format("IsDel = 0 and ServerAreaID <> {1} and ServerAreaID in (select ID from ServerArea where ProjectID = {0})", id, smodel.ServerAreaID);
            }
            DataLib.BLL.ServerPoint sBll = new DataLib.BLL.ServerPoint();
            DataTable dt = sBll.GetList(strwhere).Tables[0];
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    alreadySPName += dr["ServerPointName"].ToString() + "@";
                }
            }
            string deletespname = "";
            if(alreadySPName != "")
            {
                string[] spnames = alreadySPName.Split('@');
                for (int i = 0; i < spnames.Length; i++)
                {
                    if (spnames[i] != "")
                    {
                        deletespname += string.Format("'{0}'", spnames[i]) + ",";
                    }
                }
                deletespname = deletespname.Substring(0, deletespname.Length - 1);
            }
            string strWhere = " flag1 = '01' ";
            if (deletespname != "")
            {
                deletespname = string.Format("({0})", deletespname);
                strWhere = " flag1 = '01' and flag1 not in " + deletespname;
            }
            DataLib.BLL.City slBll = new DataLib.BLL.City();
            this.chkserverpoint.DataSource = slBll.GetList(strWhere);
            this.chkserverpoint.DataValueField = "citycode";
            this.chkserverpoint.DataTextField = "cityname";
            this.chkserverpoint.DataBind();

            foreach (ListItem li in chkserverpoint.Items)
            {

                li.Attributes.Add("onclick", "showbussinessBycity(this,1)");
                li.Attributes.Add("name", "chkpoint");
                li.Attributes.Add("code", li.Value);
            }
        }
        /// <summary>
        /// 绑定下拉列表
        /// </summary>
        private void getDropDown(DropDownList dropcjo, DropDownList droppower)
        {
            string str = " 1=1 and department = '市场部' ";
            DataLib.Accounts.Data.User uBll = new DataLib.Accounts.Data.User();
            dropcjo.DataSource = uBll.getUserList(str);
            dropcjo.DataValueField = "UserID";
            dropcjo.DataTextField = "TrueName";
            dropcjo.DataBind();

            string strWhere = " 1=1 and department = '市场部'";
            droppower.DataSource = uBll.getUserList(strWhere);
            droppower.DataValueField = "UserID";
            droppower.DataTextField = "TrueName";
            droppower.DataBind();
        }
        /// <summary>
        /// 绑定修改信息
        /// </summary>
        private void BindUpdateInfo(DataLib.Model.ServerArea samodel)
        {
            //int pointid = Convert.ToInt32(Request.QueryString["ServerPointID"].ToString());
           
            DataLib.BLL.ServerArea saBll = new DataLib.BLL.ServerArea();
            hidcjoauth.Value = saBll.GetStringByID(samodel.id, 4);
            hidcjocreate.Value = saBll.GetStringByID(samodel.id, 2);
            hidcjoshow.Value = saBll.GetStringByID(samodel.id, 3);
            hidcjoview.Value = saBll.GetStringByID(samodel.id, 1);
            hidprojectid.Value = samodel.ProjectID.ToString();

            txtareaName.Text = samodel.AreaName;
            DataTable alreadydt = saBll.GetPointList(samodel).Tables[0];
            if (alreadydt.Rows.Count > 0)
            {
                foreach (DataRow dr in alreadydt.Rows)
                {
                    foreach (ListItem chs in chkserverpoint.Items)
                    {
                        if (chs.Text == dr["ServerPointName"].ToString())
                        {
                            chs.Selected = true;
                        }
                    }
                }
            }
            if (this.chkserverpoint.Items.Count == 1)
            {
                chkserverpoint.Enabled = false;
            }
            this.Button1.Text = "保存";
        }

        /// <summary>
        /// 保存区域
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (this.txtareaName.Text.Trim() != "" && this.chkserverpoint.SelectedValue != "")
            {
                int id = 0;
                if (Request["id"] != null && Request["id"].ToString().Trim() != "")
                {
                    id = int.Parse(Request["id"].ToString());
                }
                int flag = checkisSelect();
                switch (flag)
                {
                    case -1:
                        ClientScript.RegisterStartupScript(this.GetType(), "Tip", "<script>alert('请勾选查看业务员" + this.hidcjoview.Value + "!')</script>");
                        break;
                    case -2:
                        ClientScript.RegisterStartupScript(this.GetType(), "Tip", "<script>alert('请选择授权业务员!')</script>");
                        break;
                    case -3:
                        ClientScript.RegisterStartupScript(this.GetType(), "Tip", "<script>alert('请选择开CJO人员!')</script>");
                        break;
                    case -4:
                        ClientScript.RegisterStartupScript(this.GetType(), "Tip", "<script>alert('请选择显示业务员!')</script>");
                        break;
                    default:
                        string[] arrcity = new string[flag];
                        int i = 0;
                        ServerArea samodel = new ServerArea();
                        DataLib.BLL.ServerArea sabll = new DataLib.BLL.ServerArea();
                        foreach (ListItem chs in chkserverpoint.Items)
                        {
                            if (chs.Selected == true)
                            {
                                arrcity[i] = chs.Text;
                                i++;
                            }

                        }

                        int areaid = 0;
                        if (!string.IsNullOrEmpty(Request.QueryString["areaid"]))
                        {
                            areaid = int.Parse(Request.QueryString["areaid"]);
                            samodel = sabll.GetModel(areaid);
                        }
                        else
                        {
                            samodel.id = 0;
                            samodel.CreateTime = DateTime.Now;
                            samodel.ProjectID = int.Parse(hidprojectid.Value);
                            if (Session["UserInfo"] != null)
                            {
                                DataLib.Accounts.Bus.User curUser = new DataLib.Accounts.Bus.User();
                                curUser = (DataLib.Accounts.Bus.User)Session["UserInfo"];
                                samodel.CreateMan = curUser.UserName;
                            }
                        }
                            DataLib.Model.Project p = new DataLib.BLL.Project().GetModel((int)samodel.ProjectID);
                            samodel.ProjectName = p.ProjectName;
                            samodel.ProjectNum = p.ProjectNum;
                            samodel.IsDel = false;
                            samodel.AreaName = txtareaName.Text;
                            samodel.CustomerID = p.CustomerID;
                            samodel.Customercode = p.CustomerNum;
                            samodel.CustomerName = p.CustomerName;

                        sabll.SaveArea(samodel, arrcity, hidcjoview.Value, hidcjoshow.Value, hidcjocreate.Value, hidcjoauth.Value);
                        bindList(samodel);


                        break;

                }

            }
            else 
            {
                DataLib.Common.MessageBox.Show(Page, "请输入区域名称");
            }
        }
        /// <summary>
        /// 根据服务点是否选中，来是否插入数据
        /// </summary>
        private void insertinfo(int areaid)
        {
            string strcjoview = hidcjoview.Value;
            string strcjoauth = hidcjoauth.Value;
            string strcjoshow = hidcjoshow.Value;
            string strcjocreate = hidcjocreate.Value;

            string viewusername = "";
            string viewtruename = "";
            string createusername = "";
            string createtruename = "";
            string showusername = "";
            string showtruename = "";
            string authusername = "";
            string authtruename = "";
            foreach (System.Web.UI.WebControls.ListItem chk in chkserverpoint.Items)
            {

                if (chk.Selected == true)
                {

                    viewusername = GetBussmanByMul(strcjoview, chk.Value, 0);
                    viewtruename = GetBussmanByMul(strcjoview, chk.Value, 1);

                    showusername = GetBussmanByOne(strcjoshow, chk.Value, 0);
                    showtruename = GetBussmanByOne(strcjoshow, chk.Value, 1);


                    createusername = GetBussmanByOne(strcjocreate, chk.Value, 0);
                    createtruename = GetBussmanByOne(strcjocreate, chk.Value, 1);


                    createusername = GetBussmanByOne(strcjoauth, chk.Value, 0);
                    createtruename = GetBussmanByOne(strcjoauth, chk.Value, 1);

                    DataLib.Model.ServerPoint sModel = new DataLib.Model.ServerPoint();
                    DataLib.BLL.ServerPoint sBll = new DataLib.BLL.ServerPoint();
                    DataLib.Model.ServerArea aModel = new ServerArea();
                    DataLib.BLL.ServerArea aBll = new DataLib.BLL.ServerArea();
                    aModel = aBll.GetModel(areaid);
                    if (aModel != null)
                    {
                        sModel.ServerAreaID = areaid;
                        sModel.AreaName = aModel.AreaName;
                    }

                   
                    DataLib.Accounts.Data.User uBll = new DataLib.Accounts.Data.User();

                    sModel.LookSalesmanTrueName = viewtruename;
                    sModel.LookSalesmanUserName = viewusername;

                    sModel.PowerpersonTrueName = authtruename;
                    sModel.PowerpersonUserName = authusername;

                    sModel.CjopersonTrueName = createtruename;
                    sModel.CjopersonUserName = createusername;

                    sModel.Cjoperson_show = showusername + "/" + showtruename;
                    sModel.ServerPointName = chk.Text;
                    sModel.CreateTime = DateTime.Now;
                    if (Session["UserInfo"] != null)
                    {
                        DataLib.Accounts.Bus.User curUser = new DataLib.Accounts.Bus.User();
                        curUser = (DataLib.Accounts.Bus.User)Session["UserInfo"];
                        sModel.CreateMan = curUser.UserName;
                    }

                    sBll.Add(sModel);
                }

            }
        }
        /// <summary>
        /// 删除区域事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnDel_Click(object sender, CommandEventArgs e)
        {
            int ServerPointID = Convert.ToInt32(e.CommandName);
            new DataLib.BLL.ProjectsRelation().RelationDelete(0, ServerPointID, 0, 0, 2);
            getCheckBox();
            bindList(null);
        }
        /// <summary>
        /// 按照头或者尾截取控件的文本值
        /// </summary>
        /// <param name="chkList">操作的控件ID</param>
        /// <param name="separator">截取后用什么符号分隔</param>
        /// <param name="splitType">head为截取头部，foot为截取尾部</param>
        /// <returns></returns>
        public string GetSplitChecked(CheckBoxList chkList, string separator, string splitType)
        {
            string selval = "";
            foreach (System.Web.UI.WebControls.ListItem chk in chkList.Items)
            {
                if (chk.Selected == true)
                {
                    string[] mytext = chk.Text.Split('/');
                    if (splitType == "head")
                    {
                        selval += mytext[0] + separator;
                    }
                    else
                    {
                        selval += mytext[1] + separator;
                    }
                }
            }
            return selval;
        }
        /// <summary>
        /// 判断业务员有没有漏配置
        /// </summary>
        /// <returns></returns>
        private int checkisSelect()
        {
            int isSelect = 0;
             string strcjoview = hidcjoview.Value;
            string strcjoauth = hidcjoauth.Value;
            string strcjoshow = hidcjoshow.Value;
            string strcjocreate = hidcjocreate.Value;


            foreach (System.Web.UI.WebControls.ListItem chk in chkserverpoint.Items)
            {

                if (chk.Selected == true)
                {
                    if (strcjoview.IndexOf(chk.Value) < 0)
                    {
                        isSelect = -1;
                        break;
                    }
                    else if (strcjoauth.IndexOf(chk.Value) < 0)
                    {
                         isSelect = -2;
                         break;
                    }
                    else if (strcjocreate.IndexOf(chk.Value) < 0)
                    {
                        isSelect = -3;
                        break;

                    }
                    else if (strcjoshow.IndexOf(chk.Value) < 0)
                    {
                        isSelect = -4;
                        break;
                    }
                    isSelect += 1;
                }
            }
            return isSelect;
        }
        /// <summary>
        /// 初始化CheckBoxList中哪些是选中了的
        /// </summary>
        /// <param name="selval">选中了的值串例如："0,1,1,2,1"</param>
        /// <param name="separator">值串中使用的分割符例如"0,1,1,2,1"中的逗号</param> 
        public void SetChecked(string selval, char separator)
        {
            string[] arr = selval.Split(separator);
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] != null)
                {
                    //foreach (System.Web.UI.WebControls.ListItem chk in chksalesman.Items)
                    //{
                    //    if (chk.Text.Substring(chk.Text.IndexOf('/') + 1) == arr[i])
                    //    {
                    //        chk.Selected = true;
                    //    }
                    //}
                }
            }
        }

     

       /// <summary>
        /// 选择业务员 单选格式的
        /// </summary>
        /// <param name="strval"></param>
        /// <param name="citycode"></param>
        /// <param name="flag">0用户名，1真实姓名</param>
        /// <returns></returns>
        public string GetBussmanByOne(string strval, string citycode,int flag) 
        {
            string sealman = "";
            string[] arrval = strval.Split(';');
            foreach(string str in arrval)
            {
                if (str.IndexOf(citycode) >= 0) 
                {
                    if (flag == 0)
                    {
                        sealman = str.Substring(str.IndexOf("{") + 1, str.IndexOf(",") - str.IndexOf("{") - 1);
                    }
                    else
                    {
                        sealman = str.Substring(str.IndexOf(",") + 1, str.IndexOf("}") - str.IndexOf(",") - 1);
                    }
                }
            }
            return sealman;
        }

        /// <summary>
        /// 根据checkboxlist的业务员可查看
        /// </summary>
        /// <param name="strval"></param>
        /// <param name="citycode"></param>
        /// <param name="flag">0是用户名 1是真实姓名</param>
        /// <returns></returns>
        public string GetBussmanByMul(string strval, string citycode, int flag)
        {
            string sealman = "";
            string[] arrval = strval.Split('#');
            foreach (string str in arrval)
            {
                if (str.IndexOf(citycode) >= 0)
                {
                    if (flag == 0)
                    {
                        sealman = str.Substring(str.IndexOf("{") + 1, str.IndexOf(";") - str.IndexOf("{") - 1);
                    }
                    else
                    {
                        sealman = str.Substring(str.IndexOf(";") + 1, str.IndexOf("}") - str.IndexOf(";") - 1);
                    }
                }
            }
            return sealman;
        }


        /// <summary>
        /// 绑定列表
        /// </summary>
        private void bindList(DataLib.Model.ServerArea samodel)
        {
            DataLib.BLL.ServerArea sabll = new DataLib.BLL.ServerArea();
            DataTable dt = sabll.GetPointList(samodel).Tables[0];
            this.rept.DataSource = dt;
            this.rept.DataBind();
        }
    }
}